'use strict';
const Controller = require('egg').Controller;

class SortController extends Controller {
    async index() {
        const { ctx, app } = this;
        const {
            price1,
            page = 1,
            number = 5
        } = ctx.request.query;
        // 如果page=2,则offset = 2,翻页为第二页,这个page是根据后台传进来的
        const offset = (page - 1) * number;
        let data, count; //data数据 ， count全部数据的数量
        // console.log(typeof price1);
        if (price1) {
            if (+price1 === 0) {
                data = await app.mysql.query(`select * from product limit ${offset},${number}`);
                count = await app.mysql.query(`select count(*) as count from product`);
                ctx.body = {
                    code: 0,
                    msg: "价格方式无序",
                    data: data,
                    count: count[0].count
                }
            } else if (+price1 === 1) {
                data = await app.mysql.query(`select * from product order by price desc limit ${offset},${number} `);
                count = await app.mysql.query(`select count(*) as count from product`);
                ctx.body = {
                    code: 0,
                    msg: "价格方式升序",
                    data: data,
                    count: count[0].count
                }
            } else if (+price1 === 2) {
                data = await app.mysql.query(`select * from product order by price asc limit ${offset},${number}`);
                count = await app.mysql.query(`select count(*) as count from  product`);
                ctx.body = {
                    code: 0,
                    msg: "价格方式降序",
                    data: data,
                    count: count[0].count
                }
            } else {
                ctx.body = {
                    code: 4004,
                    msg: "缺少必要参数"
                }
            }
        } else {
            ctx.body = {
                code: 4005,
                msg: "没有选择"
            }
        }
    }
}
module.exports = SortController;